﻿
Imports System.Runtime.CompilerServices
Imports osi.root.connector

Public Module _pointer
    Public Function make_pointer(Of T)(ByVal i As T) As pointer(Of T)
        Return New pointer(Of T)(i)
    End Function

    Public Function make_pointers(Of T)(ByVal ParamArray i() As T) As pointer(Of T)()
        Dim r() As pointer(Of T) = Nothing
        ReDim r(array_size(i) - 1)
        For j As Int32 = 0 To array_size(i) - 1
            r(j) = make_pointer(i(j))
        Next
        Return r
    End Function

    <Extension()> Public Sub renew(Of T)(ByRef i As pointer(Of T))
        If i Is Nothing Then
            i = New pointer(Of T)()
        Else
            i.clear()
        End If
    End Sub
End Module

Public Class pointer(Of T)
    Inherits _pointer(Of T)
    Implements IComparable(Of pointer(Of T))

    Private p As T '= Nothing, refer to weak_pointer

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal i As T)
        MyBase.New(i)
    End Sub

    Public Sub New(ByVal i As _pointer(Of T))
        MyBase.New(i)
    End Sub

    Public NotOverridable Overrides Sub clear()
        p = Nothing
    End Sub

    Public NotOverridable Overrides Function [get]() As T
        Return p
    End Function

    Public NotOverridable Overrides Sub [set](ByVal i As T)
        p = i
    End Sub

    Protected Overrides Sub Finalize()
        GC.KeepAlive(p)
        MyBase.Finalize()
    End Sub

    Public Overloads Function CompareTo(ByVal other As pointer(Of T)) As Int32 _
                                       Implements IComparable(Of pointer(Of T)).CompareTo
        Return MyBase.CompareTo(other)
    End Function
End Class
